package com.hm.base.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hm.base.auto.helper.HmSessionFactory;
import com.hm.base.auto.su.ControllerResult;
import com.hm.base.auto.su.R.LogConfig;
import com.hm.base.auto.su.R.Restful;
import com.hm.base.service.AuthorizationService;
import com.hm.base.service.DataAuthService;
import com.hm.base.vo.DataAuthSupportVo;
import com.hm.base.vo.LoginSubscriberVo;
import com.hm.base.vo.MenuVo;
import com.hm.base.vo.RoleMenuVo;
import com.hm.base.vo.RoleVo;
import com.hm.common.annotation.WebClientOperationLog;
import com.hm.common.annotation.WebClientRequestIntercept;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.ServerResponse;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午4:52:19 2017年6月2日
 * @version 1.0
 * @describe 授权信息管理
 */
@Slf4j
@ResponseBody
@RestController
@RequestMapping(Restful.API + "/auth")
public class AuthorizationApi {

	private static final String SWWAGER_TAG = "授权信息管理";

	@Autowired
	private DataAuthService dataAuthService;

	@Autowired
	private AuthorizationService authorizationService;
	
	@WebClientRequestIntercept(auth = false)
	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "用户登陆", httpMethod = "POST", notes = "用户登陆")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="用户#{#username}登陆管理平台")
	public ResponseEntity<ServerResponse<LoginSubscriberVo>> addSubscriber(
			@ApiParam(required = true, name = "username", value = "账户名称") @RequestParam("username") String username,
			@ApiParam(required = true, name = "password", value = "账户密码") @RequestParam("password") String password) {
		log.debug("用户{},试图登陆系统", username);
		return ControllerResult.success(authorizationService.login(username, password));
	}

	@RequestMapping(path = "/logout", method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "退出系统", httpMethod = "POST", notes = "退出后端系统")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="用户#{#username}登陆管理平台")
	public ResponseEntity<ServerResponse<Boolean>> logout(
			@ApiParam(required = true, name = "username", value = "账户名称") @RequestParam("username") String username) {
		log.debug("用户{},退出系统", username);

		if (CommonUtil.isEmpty(username)) {
			log.error("退出系统失败,账户名称不能为空");
			throw ServiceException.warning(ErrorCode.DATA_NOT_NULL, "账户名称不能为空");
		}

		authorizationService.logout(HmSessionFactory.currentUserId(), username);
		return ControllerResult.success(true);
	}

	@RequestMapping(path = "/user/roles", method = RequestMethod.GET)
	@ApiOperation(tags = SWWAGER_TAG, value = "加载用户角色列表", httpMethod = "GET", notes = "com.hm.base.api.AuthorizationApi::loadUserRoles")
	public ResponseEntity<ServerResponse<List<RoleVo>>> loadUserRoles(
			@ApiParam(required = false, name = "subscriberId", value = "账户ID") @RequestParam(required = false, name = "subscriberId") Long subscriberId) {
		log.debug("加载用户{}角色列表", HmSessionFactory.currentUserId());
		if (CommonUtil.isNotEmpty(subscriberId)) {
			return ControllerResult.success(authorizationService.loadUserRoles(subscriberId));
		}
		return ControllerResult.success(authorizationService.loadUserRoles(HmSessionFactory.currentUserId()));
	}

	@RequestMapping(path = "/user/menus", method = RequestMethod.GET)
	@ApiOperation(tags = SWWAGER_TAG, value = "加载用户菜单列表", httpMethod = "GET", notes = "com.hm.base.api.AuthorizationApi::loadUserMenus")
	public ResponseEntity<ServerResponse<List<MenuVo>>> loadUserMenus() {
		log.debug("加载用户{}菜单列表", HmSessionFactory.currentUserId());
		return ControllerResult.success(authorizationService.loadUserMenus(HmSessionFactory.currentUserId()));
	}

	@RequestMapping(path = "/setting/user/roles", method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "设置用户角色", httpMethod = "POST", notes = "com.hm.base.api.AuthorizationApi::settingUserRoles")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="设置用户#{#subscriberId}角色[#{#roles}]")
	public ResponseEntity<ServerResponse<Boolean>> settingUserRoles(
			@ApiParam(required = false, name = "subscriberId", value = "账户ID") @RequestParam(required = false, name = "subscriberId") Long subscriberId,
			@ApiParam(required = false, name = "roles", value = "角色ID") @RequestParam(required = false, name = "roles") List<Long> roles) {
		log.debug("用户{},设置用户角色", HmSessionFactory.currentUserId());
		if (CommonUtil.isEmpty(subscriberId)) {
			throw ServiceException.warning(ErrorCode.PARAMETERS_MISSING);
		}
		authorizationService.settingUserRoles(subscriberId, roles);
		return ControllerResult.success(true);
	}

	@RequestMapping(path = "/setting/user/role/menus", method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "设置用户角色所属菜单", httpMethod = "POST", notes = "com.hm.base.api.AuthorizationApi::settingRoleMenus")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="设置角色#{#roleId}所属菜单[#{#menus}]")
	public ResponseEntity<ServerResponse<Boolean>> settingRoleMenus(
			@ApiParam(required = false, name = "roleId", value = "角色ID") @RequestParam(required = false, name = "roleId") Long roleId,
			@ApiParam(required = false, name = "menus", value = "菜单ID") @RequestParam(required = false, name = "menus") List<Long> menus) {
		log.debug("用户{},设置用户角色", HmSessionFactory.currentUserId());
		authorizationService.settingRoleMenus(roleId, menus);
		return ControllerResult.success(true);
	}

	@RequestMapping(path = "/user/role/menus", method = RequestMethod.GET)
	@ApiOperation(tags = SWWAGER_TAG, value = "加载用户角色所属菜单", httpMethod = "GET", notes = "com.hm.base.api.AuthorizationApi::loadRoleMenus")
	public ResponseEntity<ServerResponse<List<RoleMenuVo>>> loadRoleMenus(
			@ApiParam(required = false, name = "roleId", value = "角色ID") @RequestParam(required = false, name = "roleId") Long roleId) {
		log.debug("用户{},加载用户角色所属菜单", HmSessionFactory.currentUserId());
		return ControllerResult.success(authorizationService.loadRoleMenus(roleId));
	}

	@RequestMapping(path = "/user/data/auth/codes", method = RequestMethod.PATCH)
	@ApiOperation(tags = SWWAGER_TAG, value = "加载当前登录用户所属数据权限", httpMethod = "PATCH", notes = "com.hm.base.api.AuthorizationApi::getCurrentUserDataAuthCodes")
	public ResponseEntity<ServerResponse<List<String>>> getCurrentUserDataAuthCodes() {
		log.debug("用户{},加载所属数据权限", HmSessionFactory.currentUserId());
		return ControllerResult.success(dataAuthService.getDataAuthCodesByUserId(HmSessionFactory.currentUserId()));
	}

	@RequestMapping(path = "/role/data_auth/{roleId}/{platform}", method = RequestMethod.GET)
	@ApiOperation(tags = SWWAGER_TAG, value = "加载指定角色数据权限", httpMethod = "GET", notes = "com.hm.base.api.AuthorizationApi::getDataAuthsByRoleId")
	public ResponseEntity<ServerResponse<List<DataAuthSupportVo>>> getDataAuthsByRoleId(
			@ApiParam(required = true, name = "roleId", value = "角色ID") @PathVariable("roleId") Long roleId,
			@ApiParam(required = true, name = "platform", value = "所属平台") @PathVariable("platform") String platform) {
		log.debug("用户{},加载{}角色所属数据权限", HmSessionFactory.currentUserId(), roleId);
		return ControllerResult.success(dataAuthService.getDataAuthsByRoleId(roleId, platform));
	}

	@RequestMapping(path = "/setting/role/data_auth", method = RequestMethod.POST)
	@ApiOperation(tags = SWWAGER_TAG, value = "设置指定角色数据权限", httpMethod = "POST", notes = "com.hm.base.api.AuthorizationApi::settingDataAuthsByRoleId")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="设置角色#{#roleId}数据权限:#{#dataAuthIds}")
	public ResponseEntity<ServerResponse<Boolean>> settingDataAuthsByRoleId(
			@ApiParam(required = false, name = "roleId", value = "角色ID") @RequestParam(required = false, name = "roleId") Long roleId,
			@ApiParam(required = false, name = "dataAuthIds", value = "数据权限id") @RequestParam(required = false, name = "dataAuthIds") List<Long> dataAuthIds,
			@ApiParam(required = true, name = "platform", value = "所属平台") @RequestParam(required = false, name = "platform") String platform) {
		log.debug("用户{},重置{}角色所属数据权限", HmSessionFactory.currentUserId(), roleId);
		dataAuthService.settingDataAuthsByRoleId(roleId, dataAuthIds, platform);
		return ControllerResult.success(true);
	}

	@RequestMapping(path = "/refresh/role/data_auth/{roleId}", method = RequestMethod.PATCH)
	@ApiOperation(tags = SWWAGER_TAG, value = "刷新指定角色数据权限到缓存", httpMethod = "PATCH", notes = "com.hm.base.api.AuthorizationApi::refreshDataAuthsByRoleId")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="刷新角色#{#roleId}数据权限到缓存")
	public ResponseEntity<ServerResponse<Boolean>> refreshDataAuthsByRoleId(
			@ApiParam(required = true, name = "roleId", value = "角色ID") @PathVariable("roleId") Long roleId) {
		log.debug("用户{},刷新{}角色所属数据权限到缓存", HmSessionFactory.currentUserId(), roleId);
		dataAuthService.refreshDataAuthsByRoleId(roleId);
		return ControllerResult.success(true);
	}

	@WebClientRequestIntercept(auth = false)
	@RequestMapping(path = "/refresh/data_auth", method = RequestMethod.PATCH)
	@ApiOperation(tags = SWWAGER_TAG, value = "刷新数据权限", httpMethod = "PATCH", notes = "com.hm.base.api.AuthorizationApi::refreshDataAuth")
	@WebClientOperationLog(platform=LogConfig.BUS_SYSTEM,module=LogConfig.AUTHORIZATION_MODULE,describe="刷新系统数据权限")
	public ResponseEntity<ServerResponse<Boolean>> refreshDataAuth() {
		log.debug("刷新数据权限：{}", DateUtil.now4yyyyMMddhhmm());
		return ControllerResult.success(authorizationService.refreshSystemRoleDataAuth());
	}
}
